import { Modal, Select, DatePicker } from 'antd'
import { useEffect, useState, useRef, useImperativeHandle } from 'react'
import * as echarts from 'echarts'
import { useStore } from '@/store'
import { option } from './kconst'
import { httpXp } from '@/utils'
import moment from 'moment'

import axios from 'axios'
import './index.scss'

const { RangePicker } = DatePicker

const Ordermodalopen = (props) => {

  const { loginStore } = useStore()
  const [defaultTime, setDefaultTime] = useState([moment(new Date()).add(-15, 'd'), moment(new Date())])
  const [params, setParams] = useState({
    indicator: 'DKX_MA',
    startTime: defaultTime[0],
    endTime: defaultTime[1]
  })

  const configModalOpenOk = () => {
    props.changeConfigModal('child msg')
    setConfigModalOpen(false)
  }
  const configModalOpenCancel = () => {
    props.changeConfigModal('child msg')
    setConfigModalOpen(false)
  }

  const [selIndex, setSelIndex] = useState([])
  const indexChange = (val) => {
    console.log('indexChange', val)
    setParams({
      ...params,
      indicator: val
    })
  }

  const dateOnChange = (date) => {
    console.log('dateOnChange', date)
    setDefaultTime(date)
    setParams({
      ...params,
      startTime: date[0],
      endTime: date[1],
    })
  }

  const [configModalOpen, setConfigModalOpen] = useState(false)
  const [configRow, setConfigRow] = useState({})

  const chartRef = useRef()

  // 父组件调用打开模态框
  useImperativeHandle(props.onRef, () => {
    return {
      openConfigModalOpen: openConfigModalOpen,
    }
  })
  const openConfigModalOpen = (data) => {
    setConfigModalOpen(true)
    setConfigRow({ ...data })
    setDefaultTime([moment(new Date()).add(-15, 'd'), moment(new Date())])
    setParams({
      ...params,
      freqName: data.freqName,
      featureCode: data.featureCode.split('.')[0],
      startTime: moment(new Date()).add(-15, 'd'),
      endTime: moment(new Date())
    })
  }

  useEffect(() => {
    console.log('useEffect')
    const getSelIndex = async () => {
      const { data: res_indicator } = await httpXp.get('/get_indicator')
      let list = []
      for (const key in res_indicator) {
        if (Object.hasOwnProperty.call(res_indicator, key)) {
          const el = res_indicator[key]
          if (el.WINDOW === '#0') {
            list.push({
              label: key,
              value: key,
              info: el
            })
          }
        }
      }
      setSelIndex(list)
    }
    const getKline = async () => {
      const myChart = echarts.init(chartRef.current)
      myChart.showLoading()
      let code = params.featureCode
      let start_date = params.startTime.format('YYYY-MM-DD')
      let end_date = params.endTime.format('YYYY-MM-DD')
      let ress = await axios.all([
        httpXp.get(`/get_realtime_kline?code=${code}&start_date=${start_date}&end_date=${end_date}&frequency=${params.freqName}`),
        httpXp.get('/realtime_indicator', {
          params: {
            code,
            start_date,
            end_date,
            indicator: params.indicator,
            frequency: params.freqName
          }
        })
      ])
      let { data: res } = ress[0]
      let { data: res1 } = ress[1]
      const _startTime = new Date(params.startTime).getTime() / 1000
      const _endTime = new Date(params.endTime).getTime() / 1000
      if (res[0][0] < _startTime) {
        let i = res.findIndex(item => item[0] >= _startTime)
        res = res.slice(i)
        for (const key in res1) {
          if (Object.hasOwnProperty.call(res1, key)) {
            res1[key] = res1[key].slice(i)
          }
        }
      }
      if (res.slice(-1)[0] > _endTime) {
        let i = res.findIndex(item => item[0] >= _endTime)
        res = res.slice(0, i + 1)
        for (const key in res1) {
          if (Object.hasOwnProperty.call(res1, key)) {
            res1[key] = res1[key].slice(0, i + 1)
          }
        }
      }
      option.series = []
      option.xAxis.data = res1.datetime.map(item => moment(item * 1000).format('YYYY-MM-DD HH:mm'))
      option.series[0] = {
        name: 'k线',
        type: 'candlestick',
        data: res.map(el => [el[1], el[4], el[3], el[2]])
      }
      for (const key in res1) {
        if (Object.hasOwnProperty.call(res1, key)) {
          if (key !== 'datetime') {
            const data = res1[key]
            option.series.push({
              name: key,
              type: 'line',
              symbol: 'none',
              data
            })
          }
        }
      }

      // function isSameWeek (old, now) {
      //   var oneDayTime = 1000 * 60 * 60 * 24
      //   var old_count = parseInt(+old / oneDayTime)
      //   var now_other = parseInt(+now / oneDayTime)
      //   return parseInt((old_count + 4) / 7) === parseInt((now_other + 4) / 7)
      // }

      // let markPointYdataDate = ''
      // if (configRow.freqName === '5m' || configRow.freqName === '15m' || configRow.freqName === '60m') {
      //   let list = { '5m': 5, '15m': 15, '60m': 60 }
      //   let m = Math.round(new Date(configRow.datetime).getMinutes() / list[configRow.freqName]) * list[configRow.freqName]
      //   if (m === 60) {
      //     markPointYdataDate = moment(configRow.datetime).add(1, 'h').format('YYYY-MM-DD HH:00')
      //   } else {
      //     if (m < 10) m = '0' + m
      //     markPointYdataDate = moment(configRow.datetime).format(`YYYY-MM-DD HH:${m}`)
      //   }
      // } else if (configRow.freqName === '1d') {
      //   markPointYdataDate = moment(configRow.datetime).format(`YYYY-MM-DD 00:00`)
      // } else if (configRow.freqName === '1w') {
      //   markPointYdataDate = option.xAxis.data.find(el => isSameWeek(configRow.datetime, el))
      // }
      // console.log(666, markPointYdataDate)
      // console.log(option.xAxis.data)

      let markPointYdataDate = ''
      let markPointYdataIndex = -1
      for (let index = 0; index < option.xAxis.data.length - 1; index++) {
        const date1 = option.xAxis.data[index]
        const date2 = option.xAxis.data[index + 1]
        if (new Date(date1) === new Date(configRow.datetime)) {
          markPointYdataIndex = index
          markPointYdataDate = date1
        } else if (new Date(date1) < new Date(configRow.datetime) && new Date(date2) >= new Date(configRow.datetime)) {
          markPointYdataIndex = index + 1
          markPointYdataDate = date2
        }
      }

      if (markPointYdataIndex !== -1) {
        let markPointYdata = option.series[0].data[markPointYdataIndex][3]
        option.series[0].markPoint = {
          symbol: 'triangle',
          symbolSize: [10, 12],
          animation: false,
          data: [
            {
              coord: [markPointYdataDate, markPointYdata],
              itemStyle: { color: '#FF0000' },
              symbolRotate: 180,
              label: {
                show: true,
                position: 'top',
                rotate: 0,
                color: '#f00',
                formatter: '信号点'
              }
            }
          ]
        }
      }
      console.log(option)
      if (myChart) {
        myChart.hideLoading()
        myChart.setOption(option, { notMerge: true })
      }
    }

    if (!selIndex.length) {
      getSelIndex()
    } else {
      getKline()
    }
  }, [configRow, loginStore, params, selIndex.length])

  return (
    <>
      <Modal
        className='checkKlineModal'
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <span style={{ fontSize: 14, fontWeight: 'bold' }}>{configRow.featureName}</span>
              <span style={{ marginLeft: 12 }}>{configRow.freqName}</span>
              <Select
                value={params.indicator}
                style={{ width: 215, marginLeft: 12 }}
                onChange={indexChange}
                options={selIndex}
              />
            </div>
            <RangePicker
              format="YYYY-MM-DD HH:mm"
              showTime={{
                format: 'HH:mm',
              }}
              style={{ marginRight: 60 }}
              value={defaultTime}
              onChange={dateOnChange}
            />
          </div>
        }
        open={configModalOpen}
        onOk={configModalOpenOk}
        onCancel={configModalOpenCancel}
        footer={null}
      >
        <div className='echart' ref={chartRef} style={{ height: '70vh', }}></div>
      </Modal >
    </>
  )
}
export default Ordermodalopen
